<template>
  <div>
<!--      面包屑组件-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
<!--    放置卡片组件-->
    <el-card >
<!--      放置搜索框与按钮-->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input clearable placeholder="请输入内容" v-model="queryInfo.query" @clear="getUsersList">
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
<!--      放置表格-->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" >
<!--          通过作用域插槽渲染操作列-->
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUserById(scope.row.id)"></el-button>
            <el-tooltip  effect="dark" content="分配角色" placement="top">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
<!--      放置分页-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1,2,4,8]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalUsers">
      </el-pagination>
    </el-card>
<!--    添加用户的对话框-->
    <el-dialog
      title="提示"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="handleFormClose"
      >
<!--      放置新建用户的表单-->
      <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="70px" >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddUser">确 定</el-button>
      </span>
    </el-dialog>
<!--    修改用户的对话框-->
    <el-dialog
      title="提示"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editUserDialogClosed"
      >
      <el-form :model="editUserForm" :rules="editUserFormRules" ref="editUserRef" label-width="70px" >
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data () {
    // 自定义邮箱与手机校验规则
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^[a-z\d]+(\.[a-z\d]+)*@([\da-z](-[\da-z])?)+(\.{1,2}[a-z]+)+$/
      if (regEmail.test(value)) {
      //  验证通过
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (regMobile.test(value)) {
        //  验证通过
        return callback()
      }
      callback(new Error('请输入合法的手机号码'))
    }
    return {
      //  获取用户列表的参数数据
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      //  用户列表数据
      userList: [],
      totalUsers: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 新建用户的表单数据
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 新建用户的表单校验规则
      addUserFormRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 修改用户信息的表单数据
      editUserForm: {},
      // 修改用户信息的表单校验规则
      editUserFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getUsersList()
  },
  methods: {
    // 获取用户列表的业务逻辑函数
    async getUsersList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userList = res.data.users
      this.totalUsers = res.data.total
    },
    // 单页size改变时的回调函数
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUsersList()
    },
    // 页码改变时的回调函数
    handleCurrentChange (newNum) {
      this.queryInfo.pagenum = newNum
      this.getUsersList()
    },
    // 用户状态改变的回调函数
    async userStateChanged (row) {
      const { data: res } = await this.$http.put('users/' + row.id + '/state/' + row.mg_state)
      console.log(res)
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 表单关闭时的回调函数
    handleFormClose () {
      this.$refs.addUserFormRef.resetFields()
    },
    // 表单预校验
    handleAddUser () {
      this.$refs.addUserFormRef.validate(async valid => {
        // 若校验全部通过则valid的值为true，反之则为false
        if (!valid) return
        // 可以继续下一步，发起post请求，添加新用户
        const { data: res } = await this.$http.post('users', this.addUserForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加新用户失败')
        }
        // 关闭对话框
        // 刷新用户列表
        // 提示用户添加用户成功
        this.addDialogVisible = false
        this.getUsersList()
        this.$message.success('添加新用户成功')
      })
    },
    // 展示修改用户的对话框
    async showEditDialog (id) {
      // 根据用户ID发送get请求得到该用户的信息
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
      this.editUserForm = res.data
      this.editDialogVisible = true
    },
    // 监听修改用户对话框的关闭事件
    editUserDialogClosed () {
      this.$refs.editUserRef.resetFields()
    },
    // 修改用户信息
    editUserInfo (id) {
      this.$refs.editUserRef.validate(async valid => {
        // 预验证通过则可以发起修改用户信息的请求
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editUserForm.id, {
          email: this.editUserForm.email,
          mobile: this.editUserForm.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('修改用户信息失败')
        console.log(res)
        // 关闭对话框
        // 刷新列表
        // 提示用户信息更新成功
        this.editDialogVisible = false
        this.getUsersList()
        this.$message.success('用户信息更新成功')
      })
    },
    // 根据ID删除用户
    async deleteUserById (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('取消操作成功')
      // 用户点击确定，发起根据用户ID删除用户的请求
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      this.getUsersList()
    }
  }
}
</script>

<style scoped>

</style>
